package com.example.demopay.controller;

import com.alibaba.fastjson.JSON;
import com.example.demopay.client.Client;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class PayController {

@RequestMapping("pay")
    @ResponseBody
    public Object pay() throws IOException {
    Map<String,Object> map=new HashMap<>();
    map.put("appid","wx74862e0dfcf69954");
    map.put("mchid","1558950191");
    map.put("description","999");
    map.put("out_trade_no","30220516222212124");
    map.put("notify_url","https://www.weixin.qq.com/wxpay/pay.php");
    Map<String,Object> map1=new HashMap<>();
    map1.put("total",1);
    map1.put("currency","CNY");
    map.put("amount",map1);
    String josn= JSON.toJSONString(map);

    CloseableHttpClient httpClient= Client.httpClient();

    HttpPost post=new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
    post.addHeader("Content-Type", "application/json");
    post.addHeader("Accept","application/json");

    StringEntity s=new StringEntity(josn.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");
    post.setEntity(s);
    log.info(josn.toString());

    CloseableHttpResponse response=httpClient.execute(post);

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) { //处理成功
            System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
        } else if (statusCode == 204) { //处理成功，无返回Body
            System.out.println("success");
        } else {
            System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
            throw new IOException("request failed");
        }
    } finally {
        response.close();
        Client.after(httpClient);
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(EntityUtils.toString(response.getEntity()));
    JsonNode data = root.path("code_url");
    String code_url=mapper.convertValue(data,String.class);

    Map<String,String> map2=new HashMap<>();
    map2.put("code_url",code_url);
    String json1 = JSON.toJSONString(map2);
    return json1;
}
    @RequestMapping("/payCallBack")
    @ResponseBody
    public Object payCallBack() throws IOException {
        //封装查询参数
        //4837199cf40e4ba284d6fc41eb632e41
        Map<String,String> map=new HashMap<>();
        map.put("mchid","1558950191");
        map.put("out_trade_no","30220516222212124");
        CloseableHttpClient httpClient = Client.httpClient();
        HttpGet httpGet=new HttpGet("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/30220516222212124?mchid=1558950191");
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse ret = httpClient.execute(httpGet);
        try{
            int statusCode = ret.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
                System.out.println("success,return body = " + EntityUtils.toString(ret.getEntity()));
            } else if (statusCode == 204) { //处理成功，无返回Body
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(ret.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            ret.close();
            Client.after(httpClient);
        }
        String json=EntityUtils.toString(ret.getEntity());
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(json);
        JsonNode data = root.path("trade_state");
        String retMap = mapper.convertValue(data, String.class);
        if (retMap.equals("SUCCESS")){
           return "1";
        }else {
            return "0";
        }
    }
}
